/*
 * @Description:
 * @version: 1.0.0
 * @Author: Ocean
 * @Date: 2025-07-02 15:52:02
 */
import React, { useEffect, useState } from 'react';
import { FeatureManager } from '@amcax/base';
import { userEvents } from '@app-cad/module';
import { circleBarButtons } from './config';
import {
  EnvCAD,
  useUserSettingCustomer,
} from '@app-base/common/providers/userSettingProvider';
import { CircleButton } from './CircleButton';
import { CIRCLE_BAR_EVENTS } from '@app-base/common/Constants';
import { CircleBarButtonItem } from './types';
import { KEYBOARD_VIEW } from '@app-cad/common/commands/cmd-toolbar-mouse-control';
import './style.scss';

export function CircleBar({
  isEdit,
  buttons,
  environment,
  onDrop,
}: {
  isEdit?: boolean;
  buttons?: CircleBarButtonItem[];
  environment?: string;
  onDrop?: (label: string, idx: number) => void;
}) {
  const { mouseGestureConfig, currentEnvironment } = useUserSettingCustomer();
  const [isViewControlActive, setIsViewControlActive] = React.useState(false);
  const [hoverLabel, setHoverLabel] = useState<string | null>(null);
  const [dragLabel, setDragLabel] = useState<string | null>(null);
  const [dragIdx, setDragIdx] = useState<number | null>(null);
  const [isCircleBarShow, setIsCircleBarShow] = useState(false);
  const [circleBarPosition, setCircleBarPosition] = useState({
    x: '50%',
    y: '50%',
  });
  const outerRadius = 140; // 外半径
  const innerRadius = 100; // 内半径

  useEffect(() => {
    registerEvents();
    return () => {
      unregisterEvents();
    };
  }, []);

  const registerEvents = () => {
    userEvents.on(KEYBOARD_VIEW, ({ isSelected }) => {
      setIsViewControlActive(!!isSelected);
    });
    userEvents.on(CIRCLE_BAR_EVENTS.CIRCLE_BAR_SHOW, (ev) => {
      setIsCircleBarShow(true);
      const { x, y } = ev.mouse;
      setCircleBarPosition({
        x: `${x - outerRadius}px`,
        y: `${y - outerRadius}px`,
      });
    });
    userEvents.on(CIRCLE_BAR_EVENTS.CIRCLE_BAR_HIDE, () => {
      setIsCircleBarShow(false);
    });
  };

  const unregisterEvents = () => {
    userEvents.off(KEYBOARD_VIEW);
    userEvents.off(CIRCLE_BAR_EVENTS.CIRCLE_BAR_SHOW);
    userEvents.off(CIRCLE_BAR_EVENTS.CIRCLE_BAR_HIDE);
  };

  const handleDrop = (e: React.DragEvent) => {
    e.preventDefault();
    onDrop?.(dragLabel, dragIdx);
  };

  const handleDragOver = (button: CircleBarButtonItem, idx: number) => {
    setDragLabel(button?.name);
    setDragIdx(idx);
  };

  // 直接从上下文中获取按钮数据
  const availableButtons =
    buttons ||
    (() => {
      // 如果没有传入buttons，则使用上下文中的按钮配置
      const currentEnv =
        currentEnvironment ||
        (environment as keyof typeof EnvCAD) ||
        'part_env';
      const configButtons = mouseGestureConfig?.[currentEnv] || [];

      // 将按钮名称转换为按钮对象
      return circleBarButtons(currentEnv, configButtons).filter(
        (button) =>
          !button.featureFlag ||
          FeatureManager.isFeatureEnabled(button.featureFlag),
      );
    })();

  const btnCount = availableButtons.length;
  const enableMouseGesture = mouseGestureConfig?.enableMouseGesture ?? false;

  return (
    <>
      {((isCircleBarShow && enableMouseGesture) || isEdit) && (
        <div
          className='circle-bar-container'
          onMouseLeave={() => setIsCircleBarShow(false)}
          onDragLeave={() => setHoverLabel(null)}
          style={{
            width: outerRadius * 2,
            height: outerRadius * 2,
            top: isEdit ? '0' : circleBarPosition.y,
            left: isEdit ? '0' : circleBarPosition.x,
            position: isEdit ? 'relative' : 'absolute',
          }}
        >
          <div className='circle-bar-ring' />
          <div className='circle-bar-center'>{hoverLabel}</div>
          {availableButtons.map((button, idx) => {
            const angleStep = 360 / btnCount;
            const startAngle = idx * angleStep;
            const endAngle = (idx + 1) * angleStep;
            const activated =
              button?.activated === 'isViewControlActive'
                ? isViewControlActive
                : button?.activated;
            return (
              <CircleButton
                key={idx}
                isEdit={isEdit}
                activated={typeof activated === 'boolean' ? activated : false}
                cmd={button?.cmd}
                startAngle={startAngle}
                endAngle={endAngle}
                radius={outerRadius}
                innerRadius={innerRadius}
                onHoverLabelChange={setHoverLabel}
                onHoverLabelClear={() => setHoverLabel(null)}
                onClick={() => setIsCircleBarShow(false)}
                onDragOver={() => handleDragOver(button, idx)}
                onDrop={handleDrop}
              />
            );
          })}
        </div>
      )}
    </>
  );
}
